<?php

namespace app\api\controller;

use app\admin\model\reciting\Mission;
use app\admin\model\RecitingQuestionAnswer;
use app\api\model\Homework;
use app\admin\model\Words;
use app\admin\model\WordsDetails;
use app\admin\model\WordsReviewLog;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\Request;
use OSS\OssClient;
use OSS\Core\OssException;

class NewAnswer extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = [];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /**
     * 交作业接口
     * @return void
     */
    public function saveHomework() {
        $mission_id = input('mission_id');
        $question_type = input('question_type');
        $question_num = input('question_num');
        $source_id = input('source_id');
        $score = input('score');
        $json = input('json');
    }

    /**
     * 题目自测提交接口
     * @return void
     */
    public function saveExercise() {
        $source_id = input('source_id/d'); //资源id
        $question_type = input('question_type')??0; //同步教材题型
        $question_source_type = input('question_source_type')??0; //教材类型
        $use_time = input('use_time')??0; //答题用时
        $answer_score_json = input('answer_score_json'); //答题得分数组
        $total_score = input('total_score'); //试卷总分
        $json = input('json');//试卷数据

        //json在oss上存储路径
        $object = "answer/json/".date('Y/m/d/').$this->auth->id.'_'.time().".json";
        //上传json到oss
        try{
            $config = get_addon_config('alioss');
            $bucket = $config['bucket']; //创建的项目
            $ossClient = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);

            $ossClient->putObject($bucket, $object,  htmlspecialchars_decode($json));
        } catch(OssException $e) {
            $this->error($e->getMessage().'请稍后再试！');
        }

      /*  $missionInfo = Mission::where([
            'user_id'=>$this->auth->id,
            'source_id'=>$source_id,
            'is_done'=>2
        ])->find();
        $missionInfo = false;*/
        //兼容提交作业  逻辑
        $mission_id = input('mission_id');//作业表id
        $mission_type  = 1;
        if((int)$mission_id){
            $rowa = Db::table('fa_homework')->find($mission_id);
            if($rowa){
                if($rowa['operation'] == 1){//1课后作业 2机房考试
                    $mission_type = 0;
                }
                if($rowa['operation'] == 2){ //2机房考试
                    $mission_type = 3;
                }
            }
        }
        //计算试卷得分等
        /*dump($answer_score_json);
        echo '<hr>';*/
        $answer_scores = json_decode(htmlspecialchars_decode($answer_score_json),true);
        $question_num = 0;//试卷题数
        $answer_num = 0;//答题数
        $score = 0;//得分
        $red = 0;
        $yellow = 0;
        $green = 0;
        /*dump($answer_scores);die;*/
        foreach ($answer_scores as $answer_score) {
            $question_num ++;
            if ($answer_score['score'] > 0) {
                $answer_num++;
                $score += $answer_score['score'];
            }
            switch ($answer_score['color']) {
                case 'red':
                    $red++;
                    break;
                case 'yellow':
                    $yellow++;
                    break;
                case 'green':
                    $green++;
                    break;
            }
        }
        $missionInfo = false;
        if(!$missionInfo) {
            $module = '';
            $sourcearr = ['textbook_synchronization', 'hear_say', 'listening', 'repeat', 'writing', 'soundmark', 'model', 'new_concept', 'black_plum',];
            $missionTxt = ['听说模考','单词跟读','课文跟读','线上作答','报听写','重点词组归纳','重点难点突破','考点过关精练','音标专练'];
            $resources_names = Db::name($sourcearr[$question_source_type] . '_resources')
                ->where('versionId', $source_id)
                ->field('moduleName,resourceName')
                ->find();
            foreach ($missionTxt as $vv) {
                if (strpos($resources_names['moduleName'], $vv) !== false) {
                    $module = $vv;
                }
            }

            //兼容逻辑结束
            $insertData = [
                'title' => $resources_names['resourceName']??'',
                'mission_id'=>$mission_id??0,
                'mission_type'=>$mission_type??1,
                'gread_id'=>(int)$this->auth->grade_id,
                'class_id'=>(int)$this->auth->class_id,
                'user_id' => $this->auth->id,
                'source_id'=>$source_id??'',
                'module'=>$module,
                'question_num'=>$question_num,
                'answer_num'=>$answer_num,
                'use_time' => self::secondsToHoursMinutes($use_time),
                //'json'=>$json?htmlspecialchars_decode($json):null,
                'json'=>'http://xckj-auto-file-res.oss-cn-shenzhen.aliyuncs.com/'.$object,//将oss完整路径存储进json
                'answer_score_json' => htmlspecialchars_decode(input('answer_score_json')),
                'score'=>round($score,1)??0,
                'full_score'=>$total_score,
                'question_type' => $question_type,
                'question_source_type'=>$question_source_type,
                //'is_done'=>$answer_num>=$question_num?1:2,
                'is_done'=>1,
                'green'=>$green,
                'yellow'=>$yellow,
                'red'=>$red,
            ];
            $missionInfo = new Mission();
            $missionInfo->save($insertData);
        } else {
            $missionInfo->mission_id    = $mission_id??0;
            $missionInfo->mission_type  = $mission_type??1;
            $missionInfo->answer_num    = $answer_num;
            $missionInfo->use_time      = $use_time;
            //$missionInfo->json          = json_decode(htmlspecialchars_decode($json));
            $missionInfo->json          = 'http://xckj-auto-file-res.oss-cn-shenzhen.aliyuncs.com/'.$object;//将oss完整路径存储进json
            $missionInfo->answer_score_json          = htmlspecialchars_decode(input('answer_score_json'));
            $missionInfo->score         = $score;
            $missionInfo->is_done       = $answer_num>=$question_num?1:2;
            $missionInfo->green         = $green;
            $missionInfo->yellow        = $yellow;
            $missionInfo->red           = $red;
            $missionInfo->save();
        }
        $missionInfo->json = json_decode(htmlspecialchars_decode($json));
        $missionInfo->msg  = get_mission_msg($score);
        $this->success('提交成功',$missionInfo);
    }

    public function getExerciseDetail() {
        $id = input('rm_id'); //练习id
        $missionInfo = Mission::where('id',$id)->find();
        if($missionInfo) {
            $missionInfo->json = $missionInfo->json?json_decode(htmlspecialchars_decode(file_get_contents($missionInfo->json))):'';//将oss中存储的json内容返回给前端
            $missionInfo->msg = get_mission_msg($missionInfo->score);
            $this->success('获取成功',$missionInfo);
        } else {
            $this->error('您查询的记录不存在！');
        }
    }

    public static function secondsToHoursMinutes($seconds) {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds % 3600) / 60);
        $seconds = $seconds % 60;
        $str = '';
        if(!empty($hours)){
            $str.=$hours."h ";
        }
        if(!empty($minutes)){
            $str.=$minutes."min ";
        }
        if(!empty($seconds)){
            $str.=$seconds."s";
        }
        return $str;
    }
}